/* 
 * Copyright (C) 2001-2003 Jacek Sieka, j_s@telia.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "stdinc.h"
#include "DCPlusPlus.h"

#include "ClientManager.h"

#include "ShareManager.h"
#include "SearchManager.h"
#include "CryptoManager.h"
#include "ConnectionManager.h"
#include "HubManager.h"

//#include "AdcHub.h"
//#include "NmdcHub.h"
//Sulan start svn203
#include "RegexpHandler.h"
//End
Client* ClientManager::getClient(/*const string& aHubURL*/) {
	Client* c = new Client();

	{
		Lock l(cs);
		clients.push_back(c);
	}

	c->addListener(this);
	return c;
}

void ClientManager::putClient(Client* aClient) {
	aClient->disconnect();
	fire(ClientManagerListener::CLIENT_DISCONNECTED, aClient);
	aClient->removeListeners();

	{
		Lock l(cs);
		clients.remove(aClient);
	}
	delete aClient;
}

void ClientManager::infoUpdated() {
	Lock l(cs);
	for(Client::Iter i = clients.begin(); i != clients.end(); ++i) {
		if((*i)->isConnected()) {
			(*i)->myInfo();
		}
	}
}

void ClientManager::onClientSearch(Client* aClient, const string& aSeeker, int aSearchType, const string& aSize, 
									int aFileType, const string& aString) throw() {

	// Filter own searches
	if(SETTING(CONNECTION_TYPE) == SettingsManager::CONNECTION_ACTIVE) {
		if(aSeeker.find(aClient->getLocalIp()) != string::npos) {
			return;
		}
	} else {
		if(aSeeker.find(aClient->getNick()) != string::npos) {
			return;
		}
	}
	
	string::size_type pos = aSeeker.find("Hub:");
	// We don't wan't to answer passive searches if we're in passive mode...
	if(pos != string::npos && SETTING(CONNECTION_TYPE) != SettingsManager::CONNECTION_ACTIVE) {
		return;
	}
	// CDM EXTENSION BEGINS
	string ip, file;
	short port = 0;
	if(pos == string::npos) {
		Util::decodeUrl(aSeeker, ip, port, file);
		string nick(aClient->getNickFromUserIp(ip));
		if(!nick.empty()) {
			getUser(aClient->getNickFromUserIp(ip), aClient, false)->setSearchPort(port);
		}
	}
	// CDM EXTENSION ENDS
	SearchResult::List l;
	ShareManager::getInstance()->search(l, aString, aSearchType, aSize, aFileType, aClient, (pos == string::npos) ? 10 : 5);
//		dcdebug("Found %d items (%s)\n", l.size(), aString.c_str());
	if(l.size() > 0) {
		if(pos != string::npos) {
			string name = aSeeker.substr(4);
			// Good, we have a passive seeker, those are easier...
			string str;
			for(SearchResult::Iter i = l.begin(); i != l.end(); ++i) {
				SearchResult* sr = *i;
				str += sr->toSR();
				str[str.length()-1] = 5;
				str += name;
				str += '|';

				sr->decRef();
			}
			
			if(str.size() > 0)
				aClient->searchResults(str);
			
		} else {
			try {
				// CDM EXTENSION BEGINS
				//string ip, file;
				//short port = 0;
				//Util::decodeUrl(aSeeker, ip, port, file);
				// CDM EXTENSION ENDS
				ip = Socket::resolve(ip);
				if(port == 0) port = 412;
				for(SearchResult::Iter i = l.begin(); i != l.end(); ++i) {
					SearchResult* sr = *i;
					s.writeTo(ip, port, sr->toSR());
					sr->decRef();
				}
			} catch(const SocketException& /* e */) {
				dcdebug("Search caught error\n");
			}
		}
	}
}

User::Ptr ClientManager::getUser(const string& aNick, const string& aHint /* = Util::emptyString */) {
	Lock l(cs);
	dcassert(aNick.size() > 0);
	UserPair p = users.equal_range(aNick);

	if(p.first == p.second) {
		User::Ptr& u = users.insert(make_pair(aNick, new User(aNick)))->second;
		u->setLastHubAddress(aHint);
		return u;
	}

	UserIter i;
	if(aHint.empty()) {
		// No hint, first, try finding an online user...
		for(i = p.first; i != p.second; ++i) {
			if(i->second->isOnline()) {
				return i->second;
			}
		}
		// Blah...return the first one...doesn't matter now...
		return p.first->second;
	}

	// Since we have a hint, make sure we use it...
	for(i = p.first; i != p.second; ++i) {
		if(i->second->getLastHubAddress() == aHint) {
			return i->second;
		}
	}
	// Since old dc++'s didn't return port in $SR's we'll check for port-less hints as well
	string::size_type k = aHint.find(':');
	if(k != string::npos) {
		string hint = aHint.substr(0, k); 
		for(i = p.first; i != p.second; ++i) {
			if(i->second->getLastHubAddress() == hint) {
				return i->second;
			}
		}
	}
	
	// Try to find an online user, higher probablility that it's one of these...
	for(i = p.first; i != p.second; ++i) {
		if(i->second->isOnline()) {
			return i->second;
		}
	}

	User::Ptr& u = users.insert(make_pair(aNick, new User(aNick)))->second;
	return u;
}

User::Ptr ClientManager::getUser(const string& aNick, Client* aClient, bool putOnline /* = true */) {
	Lock l(cs);
	dcassert(aNick.size() > 0);
	dcassert(aClient != NULL);
	dcassert(find(clients.begin(), clients.end(), aClient) != clients.end());

	UserPair p = users.equal_range(aNick);
	UserIter i;

	// Check for a user already online
	for(i = p.first; i != p.second; ++i) {
		if(i->second->isClient(aClient)) {
			return i->second;
		}
	}

	// Check for an offline user that was on that hub that we can put online again
	for(i = p.first; i != p.second; ++i) {
		if( (!i->second->isOnline()) && 
			((i->second->getLastHubAddress() == aClient->getAddressPort()) || (i->second->getLastHubAddress() == aClient->getIpPort())) )
		{
			if(putOnline) {
				i->second->setClient(aClient);
				fire(ClientManagerListener::USER_UPDATED, i->second);
			}
			return i->second;
		}
	}

	// Check for any offline user
	for(i = p.first; i != p.second; ++i) {
		if( (!i->second->isOnline()) ) {
			if(putOnline) {
				i->second->setClient(aClient);
				fire(ClientManagerListener::USER_UPDATED, i->second);
			}
			return i->second;
		}
	}
	
	// Create a new user
	User::Ptr& u = users.insert(make_pair(aNick, new User(aNick)))->second;
	if(putOnline) {
		u->setClient(aClient);
		fire(ClientManagerListener::USER_UPDATED, u);
	}
	return u;
}

void ClientManager::on(TimerManagerListener::Minute, u_int32_t /* aTick */) throw() {
	Lock l(cs);

	// Collect some garbage...
	UserIter i = users.begin();
	while(i != users.end()) {
		if(i->second->unique()) {
			users.erase(i++);
		} else {
			++i;
		}
	}

	for(Client::Iter j = clients.begin(); j != clients.end(); ++j) {
		if((*j)->lastCounts != Client::counts) {
			dcdebug("(*j)->lastCounts = %d\n", (*j)->lastCounts);
			dcdebug("Client::counts = %d\n", Client::counts);
			(*j)->myInfo();
		}
	}
}

void ClientManager::onClientLock(Client* client, const string& aLock) throw() {
	if(CryptoManager::getInstance()->isExtended(aLock)) {
		StringList feat = features;
		if(BOOLSETTING(COMPRESS_TRANSFERS))
			feat.push_back("GetZBlock");
		client->supports(feat);
	}
	client->key(CryptoManager::getInstance()->makeKey(aLock));
	client->validateNick(client->getNick());
}
// ClientListener

void ClientManager::on(HubName, Client* client) throw() { 
	fire(ClientManagerListener::CLIENT_UPDATED, client);
}
void ClientManager::on(RawMessage, Client* client, const string& line) throw() {
	fire(ClientManagerListener::MESSAGE, client, line);
}

void ClientManager::on(ConnectToMe, Client* client,  const string& line1, const string& line2){
	ConnectionManager::getInstance()->connect(line1, (short)Util::toInt(line2), client->getNick());
}
void ClientManager::on(CLock, Client* client, const string& line1, const string&) throw() {
	onClientLock(client, line1);
}
void ClientManager::on(RevConnectToMe, Client* client, const User::Ptr& user) throw() {
	if(SETTING(CONNECTION_TYPE) == SettingsManager::CONNECTION_ACTIVE) {
		client->connectToMe(user);
	}
}

void ClientManager::on(Search, Client* aClient, const string& aSeeker, int aSearchType, const string& aSize, 
						int aFileType, const string& aString) throw() {
		fire(ClientManagerListener::INCOMING_SEARCH, aSeeker, aString);
		onClientSearch(aClient, aSeeker, aSearchType, aSize, aFileType, aString);
}



// SearchManagerListener
void ClientManager::on(SearchManagerListener::SR, SearchResult *sr) throw() {
	if (SETTING(CONNECTION_TYPE) == SettingsManager::CONNECTION_ACTIVE) {
		// if active, this contains an IP address
		User::updated(sr->getUser());
	}
}
// CDM EXTENSION BEGINS

void ClientManager::multiHubKick(User::Ptr& aUser, const string& aReason) {
	if (aUser) {
		//Sulan start svn 168
		User::List userList = findUser(aUser, false);
		for(User::Iter k = userList.begin(); k != userList.end(); ++k) {
			if((*k)->isCheckable(false))(*k)->kick(aReason); 
		}
		//End
	}
		
}
//Sulan
void ClientManager::reloadFavHubs(){
	Lock l(cs);
	for(Client::Iter j = clients.begin(); j != clients.end(); ++j) {
		(*j)->reloadFavHubs();
	}
}
// pothead extension starts #3
//Sulan start svn 168
void ClientManager::multiHubRaw(int aRaw, User::Ptr& aUser) {
	if (aUser) {
		User::List userList = findUser(aUser, false);
		for(User::Iter k = userList.begin(); k != userList.end(); ++k) {
			if((*k)->isCheckable(false))(*k)->sendRawCommand(aRaw, Client::CONTEXT_RAW_MULTIHUB); 
		}	
//End
	}
}

// pothead extension starts #8
bool ClientManager::CheckSharingHub(User::Ptr& aUser) {
	Lock l(cs);
	//Sulan start svn 168
	if (aUser) {
		User::List userList = findUser(aUser, true);
		for(User::Iter k = userList.begin(); k != userList.end(); ++k) {
			if(!(*k)->getClient()->getHideShare()){
				return true;
			}
		}
		
	}
	return false;
	//End
}
// pothead extension starts (r2 code) svn62
void ClientManager::multiHubBanIp(const string& aIp, const string& aReason) { 
	Lock l(cs); 
	for(Client::Iter i = clients.begin(); i != clients.end(); ++i) {
		string banstring = ("<" + (*i)->getNick() + "> " + (*i)->getTrigger() + "banip " + aIp + " " + aReason + ".|");
		//Sulan start svn66
		if((*i)->getTrigger().empty()) { return; }
		//End
		(*i)->send(banstring);
	}
}
// pothead starts svn162 svn179
int ClientManager::getTotalUsers() {
	int totalUserCount = 0;
	Lock l(cs);
	for(Client::Iter i = clients.begin(); i != clients.end(); ++i)
		totalUserCount += (*i)->getUserCount();
	return totalUserCount;
}

void ClientManager::on(Failed, Client* client, const string&) throw() { 
	HubManager::getInstance()->removeUserCommand(client->getAddressPort());
	fire(ClientManagerListener::CLIENT_DISCONNECTED, client);
}

void ClientManager::on(UserCommand, Client* client, int aType, int ctx, const string& name, const string& command) throw() { 
	if(BOOLSETTING(HUB_USER_COMMANDS)) {
 		HubManager::getInstance()->addUserCommand(aType, ctx, ::UserCommand::FLAG_NOSAVE, name, command, client->getAddressPort());
	}
}
int64_t ClientManager::getTotalShare() {
	int64_t totalShare = 0;
	Lock l(cs);
	for(Client::Iter i = clients.begin(); i != clients.end(); ++i)
		totalShare += (*i)->getAvailable();
	return totalShare;
}
// pothead ends
//Sulan start svn 168
bool ClientManager::isHubCountFaking(User::Ptr& aUser, const int statedHubs) {
	//Go look in all hubs for this user..
	Lock l(cs);
	User::List userList = findUser(aUser, false);
	string hubsAndNicks;
	int connectedHubs = userList.size();

	for(User::Iter k = userList.begin(); k != userList.end(); ++k) {
		hubsAndNicks+= "\r\n [> " + (*k)->getNick() + " [ " + (*k)->getClient()->getAddress() + " ]" + " [ " +Util::toString((*k)->getBytesShared()) + " B ]" + " [ " + (*k)->getEmail() + " ]";
	}

	//Set ev. fakehubcount
	if(statedHubs < connectedHubs){
		for(User::Iter k = userList.begin(); k != userList.end(); ++k) {
			(*k)->setFakeHubCounts(userList.size(), hubsAndNicks);
		}
		return true;
	}else{
		aUser->setConnectedHubs(connectedHubs);
		aUser->setKnownHubsString(hubsAndNicks);
	}
	return false;
}

User::List ClientManager::findUser(User::Ptr& aUser, bool forFilelist){
	User::List userList;
	//Find all matching users and add them to a list, then return the list;
	for(Client::Iter i = clients.begin(); i != clients.end(); ++i) {
		User::Ptr user = (*i)->findUser(aUser->getBytesShared(), aUser->getHisIp(), aUser->getEmail(), aUser->getConnection(), aUser->getHubs(), forFilelist);
		if(user){
			userList.push_back(user);
		}
			
	}
	return userList;
}
//End
// CDM EXTENSION ENDS

string ClientManager::findNickIp(const string& aHint){
	string ret;
	bool isIp = RegexpHandler::isIp(aHint);
	//Find all matching users and add them to a list, then return the list;
	string found;
	int hits = 0;
	for(Client::Iter i = clients.begin(); i != clients.end(); ++i) {
		string tmp = (*i)->findNickIp(aHint, isIp);
		if(!tmp.empty()){
			found += "\r\n";
			found += tmp;
			++hits; 
		}
	}
	ret += "*** Found ";
	ret += Util::toString(hits);
	if(isIp)
		ret += " hits on ip ";
	else		
		ret += " hits on nick ";
	ret += aHint;
	ret += "\r\n";
	ret += found;

	return ret;
}
/**
 * @file
 * $Id: ClientManager.cpp 272 2005-07-19 15:58:40Z Pothead $
 */